<template>
  <div class="lizhi-form">
    <div class="lizhi-form-header">
      <router-link
        to="/main/renshi/renshidiaodong/yuangonglizhi/yuangonglizhi"
        style=""
        ><el-button type="primary" icon="el-icon-back">返回</el-button></router-link
      >
      <span
        style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px"
      >
      <el-button type="success" icon="el-icon-plus" @click="saveData" v-if="!isView">保存</el-button>
        <el-button type="" icon="el-icon-menu" @click="goToList">列表</el-button>
        <!-- <button @click="printToPDF">打印PDF</button> -->
        <el-button type="info" icon="el-icon-printer" @click="printForm"
          >打印</el-button
        >
      </span>
    </div>
    <div class="resignation-form">
      <h2>职员/员工离职申请表</h2>
      <div style="display: flex; justify-content: space-between">
        <label
          >部门：<input v-model="formData.department" :disabled="isView"
        /></label>
        <label
          >组别：<input v-model="formData.groupName" :disabled="isView"
        /></label>
        <label>
          <input
            type="radio"
            v-model="formData.resignType"
            value="辞职"
            :disabled="isView"
          />辞职
        </label>
        <label>
          <input
            type="radio"
            v-model="formData.resignType"
            value="其它"
            :disabled="isView"
          />其它
        </label>
        <label
          >填表日期：
          <input
            v-model="formData.fillDateYear"
            type="number"
            style="width: 50px"
            :disabled="isView"
          />
          年
          <input
            v-model="formData.fillDateMonth"
            type="number"
            style="width: 40px"
            :disabled="isView"
          />
          月
        </label>
      </div>
      <table border="1" style="width: 100%; text-align: center">
        <tr>
          <td>姓名</td>
          <td>职务</td>
          <td>工号</td>
          <td>性别</td>
          <td>进厂日期</td>
          <td>离厂日期</td>
        </tr>
        <tr>
          <td><input v-model="formData.name" :disabled="isView" /></td>
          <td><input v-model="formData.position" :disabled="isView" /></td>
          <td><input v-model="formData.employeeId" :disabled="isView" /></td>
          <td><input v-model="formData.gender" :disabled="isView" /></td>
          <td><input v-model="formData.joinDate" :disabled="isView" /></td>
          <td><input v-model="formData.leaveDate" :disabled="isView" /></td>
        </tr>
        <tr>
          <td>
            <span>个人陈述理由<br />（仅限辞职/辞退）</span>
          </td>
          <td colspan="5">
            <textarea
              v-model="formData.reason"
              style="width: 100%; height: 100px"
              :disabled="isView"
            ></textarea>
          </td>
        </tr>

        <tr>
          <td>
            <span>班（组）长意见</span>
          </td>
          <td colspan="5">
            <div>
              <textarea
                v-model="formData.teamLeaderOpinion"
                style="width: 100%; height: 100px"
                :disabled="isView"
              ></textarea>

              <label
                >班（组）长：<input
                  v-model="formData.teamLeaderName"
                  :disabled="isView" /></label
              >&emsp;&emsp;&emsp;
              <input
                v-model="formData.teamLeaderDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.teamLeaderDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>
        <tr>
          <td rowspan="4">
            <span>部门意见</span>
          </td>
          <td colspan="5">
            <div>
              <textarea
                v-model="formData.supervisorOpinion"
                style="width: 100%; height: 100px"
                :disabled="isView"
              ></textarea>
              <label
                >主管：<input
                  v-model="formData.supervisorName"
                  :disabled="isView" /></label
              >&emsp;&emsp;&emsp;
              <input
                v-model="formData.supervisorDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.supervisorDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="5">
            <div>
              <textarea
                v-model="formData.managerOpinion"
                style="width: 100%; height: 100px"
                :disabled="isView"
              ></textarea>
              <label
                >经理：<input
                  v-model="formData.managerName"
                  :disabled="isView" /></label
              >&emsp;&emsp;&emsp;
              <input
                v-model="formData.managerDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.managerDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="5">
            <div>
              <textarea
                v-model="formData.directorOpinion"
                style="width: 100%; height: 100px"
                :disabled="isView"
              ></textarea>
              <label
                >部长/总监：<input
                  v-model="formData.directorName"
                  :disabled="isView" /></label
              >&emsp; &emsp;&emsp;
              <input
                v-model="formData.directorDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.directorDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>

        <tr>
          <td colspan="5">
            <div>
              <textarea
                v-model="formData.generalManagerOpinion"
                style="width: 100%; height: 100px"
                :disabled="isView"
              ></textarea>
              <label
                >总经理：<input
                  v-model="formData.generalManagerName"
                  :disabled="isView" /></label
              >&emsp;&emsp;&emsp;
              <input
                v-model="formData.generalManagerDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.generalManagerDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>

        <tr>
          <td rowspan="2">
            <div class="section-title">企业管理部核</div>
          </td>
          <td colspan="2">
            <div>
              <label
                >人资经理：<input
                  v-model="formData.hrManagerName"
                  :disabled="isView" /></label
              ><br />&emsp;&emsp;
              <input
                v-model="formData.hrManagerDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.hrManagerDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
          <td rowspan="2">
            <div class="section-title">总裁/董事长批准</div>
          </td>
          <td rowspan="2" colspan="2">
            <div class="approval-section">
              <label
                >总裁/董事长：<input
                  v-model="formData.presidentName"
                  :disabled="isView" /></label
              ><br />&emsp;&emsp;
              <input
                v-model="formData.presidentDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.presidentDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <div>
              <label
                >部 长：<input
                  v-model="formData.departmentHeadName"
                  :disabled="isView" /></label
              ><br />&emsp;&emsp;
              <input
                v-model="formData.departmentHeadDateYear"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              年
              <input
                v-model="formData.departmentHeadDateMonth"
                type="number"
                style="width: 40px"
                :disabled="isView"
              />
              月
            </div>
          </td>
        </tr>
      </table>

      <div class="instruction">
        <ol>
          说明：
          <li>
            1.主管级以下人员（含主管级），经分公司部长/总监/总经理核准，企业管理部批示后，方可办理离职手续；
          </li>
          <li>
            2.经理级以上人员，由分公司部长/总监/总经理核准，企业管理部批示后，需由总裁批准，方可办理离职手续。
          </li>
        </ol>
      </div>
      <p style="display: flex; justify-content: space-between">
        <span>表单编号及版本：AM-JY-057 A/2 </span><span>保存期限：长期</span>
      </p>
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { Message } from "element-ui";
import {
  saveResignationApplication,
  getResignationApplicationDetail,
} from "@/api/resignationApplication";

export default {
  data() {
    return {
      id: null,
      isView: false,
      isEdit: false,
      formData: {
        department: "",
        groupName: "",
        resignType: "",
        fillDateYear: null,
        fillDateMonth: null,
        name: "",
        position: "",
        employeeId: "",
        gender: "",
        joinDate: "",
        leaveDate: "",
        reason: "",
        teamLeaderOpinion: "",
        teamLeaderName: "",
        teamLeaderDateYear: null,
        teamLeaderDateMonth: null,
        supervisorOpinion: "",
        supervisorName: "",
        supervisorDateYear: null,
        supervisorDateMonth: null,
        managerOpinion: "",
        managerName: "",
        managerDateYear: null,
        managerDateMonth: null,
        directorOpinion: "",
        directorName: "",
        directorDateYear: null,
        directorDateMonth: null,
        generalManagerOpinion: "",
        generalManagerName: "",
        generalManagerDateYear: null,
        generalManagerDateMonth: null,
        hrManagerName: "",
        hrManagerDateYear: null,
        hrManagerDateMonth: null,
        departmentHeadName: "",
        departmentHeadDateYear: null,
        departmentHeadDateMonth: null,
        presidentName: "",
        presidentDateYear: null,
        presidentDateMonth: null,
      },
    };
  },
  created() {
    // 获取路由参数
    const { id, type } = this.$route.query;
    console.log("路由参数:", this.$route.query);
    if (id) {
      this.id = id;
      if (type === "view") {
        this.isView = true;
      } else if (type === "edit") {
        this.isEdit = true;
      }
      console.log(
        "获取详情ID:",
        id,
        "查看模式:",
        this.isView,
        "编辑模式:",
        this.isEdit
      );
      this.getDetail(id);
    } else {
      console.log("没有ID参数，创建新表单");
      // 设置默认值
      const now = new Date();
      this.formData.fillDateYear = now.getFullYear();
      this.formData.fillDateMonth = now.getMonth() + 1;
    }
  },
  methods: {
    // 获取详情
    async getDetail(id) {
      try {
        console.log("开始获取详情，ID:", id);
        const response = await getResignationApplicationDetail(id);
        console.log("获取详情响应:", response);

        if (response.data && response.data.code === 200) {
          const data = response.data.data;
          console.log("后端返回的数据:", data);

          if (!data) {
            console.error("后端返回的数据为空");
            Message.error("获取详情失败：数据为空");
            return;
          }

          // 将后端数据赋值给表单
          this.formData = data;

          console.log("设置后的表单数据:", this.formData);

          // 强制更新视图
          this.$forceUpdate();
        } else {
          console.error("获取详情失败:", response.data);
          Message.error(response.data?.message || "获取详情失败");
        }
      } catch (error) {
        console.error("获取详情错误：", error);
        Message.error("获取详情失败：" + (error.message || "未知错误"));
      }
    },

    // 跳转到列表页
    goToList() {
      this.$router.push("/main/renshi/renshizhidu/lizhisqd/lizhisqdList");
    },

    // 验证表单
    validateForm() {
      console.log("开始验证表单数据:", this.formData);

      if (!this.formData.department) {
        Message.error("请填写部门");
        return false;
      }
      if (!this.formData.name) {
        Message.error("请填写姓名");
        return false;
      }
      if (!this.formData.position) {
        Message.error("请填写职务");
        return false;
      }
      if (!this.formData.employeeId) {
        Message.error("请填写工号");
        return false;
      }
      if (!this.formData.joinDate) {
        Message.error("请填写进厂日期");
        return false;
      }
      if (!this.formData.leaveDate) {
        Message.error("请填写离厂日期");
        return false;
      }
      if (!this.formData.reason) {
        Message.error("请填写个人陈述理由");
        return false;
      }

      return true;
    },

    // 保存数据
    async saveData() {
      if (!this.validateForm()) {
        return;
      }

      try {
        console.log("准备保存数据...");

        // 设置ID（如果是编辑模式）
        if (this.isEdit) {
          this.formData.id = this.id;
        }

        console.log("提交的数据:", this.formData);
        const response = await saveResignationApplication(this.formData);
        console.log("保存响应:", response);

        if (response.data && response.data.code === 200) {
          Message.success("保存成功");
          // 保存成功后跳转到列表页
          this.$router.push("/main/renshi/renshizhidu/lizhisqd/lizhisqdList");
        } else {
          console.error("保存失败:", response.data);
          Message.error(response.data?.message || "保存失败");
        }
      } catch (error) {
        console.error("保存错误：", error);
        Message.error("保存失败：" + (error.message || "未知错误"));
      }
    },

    async printToPDF() {
      const doc = new jsPDF("p", "pt", "a4");
      const element = document.querySelector(".resignation-form");
      await html2canvas(element).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");
        const imgWidth = 522;
        const pageHeight = 841.89;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let positionY = 0;
        if (imgHeight >= pageHeight) {
          let leftHeight = imgHeight;
          while (leftHeight >= pageHeight) {
            doc.addImage(imgData, "PNG", 40, positionY, imgWidth, pageHeight);
            positionY += pageHeight;
            doc.addPage();
            leftHeight -= pageHeight;
          }
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, leftHeight);
        } else {
          doc.addImage(imgData, "PNG", 40, positionY, imgWidth, imgHeight);
        }
      });
      doc.save("职员/员工离职申请表.pdf");
    },
    printForm() {
      window.print();
    },
  },
};
</script>

<style scoped lang="scss">
.lizhi-form {
  width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
  padding: 20px;
  background-color: #fff;
}

.lizhi-form-header {
  display: flex;
  justify-content: space-between;
}

.resignation-form {
  /* border: 1px solid #000; */
  padding: 10px;
  margin-top: 10px;

  label {
    display: flex;
    align-items: center;
  }
}

table {
  border-collapse: collapse;
  width: 100%;
  margin-top: 10px;
}

th,
td {
  border: 1px solid #000;
  padding: 5px;
}

input {
  background-color: transparent;
  outline: none;
  border: none;
  border-bottom: 1px solid #000;
  line-height: 20px;
}

input:disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
  opacity: 0.7;
}

textarea:disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
  opacity: 0.7;
}

.instruction {
  text-align: left;
  line-height: 35px;
}

li {
  /* 取消li的序号 */
  list-style: none;
}
@media print {
    .lizhi-form{
        margin: 0px;
        padding: 0px;
        width: 280mm;
    }
    textarea{
        width: 95% !important;
        resize: none !important;
    }
  .lizhi-form-header {
    display: none;
  }
}
</style>